# Definition for a binary tree node.
from typing import List, Optional


class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


class Solution:
    def buildTree(self, inorder: List[int], postorder: List[int]) -> Optional[TreeNode]:
        if len(inorder) == 0 or len(postorder) == 0:
            return None

        val = postorder[-1]

        idx = inorder.index(val)
        in_left = inorder[0:idx]
        in_right = inorder[idx + 1:]

        post_left = postorder[0:len(in_left)]
        post_right = postorder[len(in_left):len(postorder) - 1]

        node = TreeNode(val=val,
                        left=self.buildTree(in_left, post_left),
                        right=self.buildTree(in_right, post_right))
        return node
